import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { DomSanitizer, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
import { Propertylist } from '../../interface';
import { ConfirmationService, MenuItem } from 'primeng/api';
import { ContentService } from '../../../layout/admin/service/content.service';
import { MessageService } from 'primeng/components/common/messageservice';
import { ProjectService } from '../../service/project.service';
import { HttpClient } from '@angular/common/http';
import { CountryUtilsService } from '../../../shared/services/country-utils.service';
import * as _ from 'lodash';
import * as coordtransform from 'coordtransform';
import { PropertyService } from '../../service/property.service';
import { AbmComponent } from 'angular-baidu-maps';
import { PropertySaleStatus, CRUD_MODE, UserRoles } from '../../../shared/config/app-settings';
import { Router, ActivatedRoute } from '@angular/router';
import { UserService } from '../../../shared/services/user.service';
import { Location } from '@angular/common';
declare const BMap: any;
declare const BMAP_SATELLITE_MAP: any;

@Component({
  selector: 'app-project-detail-view',
  templateUrl: './project-detail-view.component.html',
  styleUrls: ['./project-detail-view.component.scss'],
})
export class ProjectDetailViewComponent implements OnInit {
  project: any = {};
  mainImages: any[];
  properties: any[] = [];
  options: any = {};
  mapGoogleType: boolean = true;
  user:any;
  previewImgSrc: string;
  imgPreview: boolean = false;
  @Input() id;
  cols: any[];
  private _map: any;
  constructor(
    public sanitizer: DomSanitizer,
    private confirmationService: ConfirmationService,
    private contentService: ContentService,
    private messageService: MessageService,
    private projectService: ProjectService,
    private propertyService: PropertyService,
    private httpClient: HttpClient,
    private router:Router,
    private location: Location,
    private route:ActivatedRoute,
    private userService:UserService,
    private countryUtilsService: CountryUtilsService,

  ) {


  }

  ngOnChanges() {
    // TODO
  }

  ngOnInit() {
    this.getCurrentUser();
    this.initPropertyList();
    this.cols = [
      // { field: 'id', header: 'ID', with: "50px" },
      // { field: 'type', header: 'TYPE', with: "150px" },
      { field: 'lot', header: 'LOT#'  },
      { field: 'bedroomCount', header: 'BED'  },
      { field: 'bathRoomCount', header: 'BATH'  },
      { field: 'parkingCount', header: 'PARKING'  },
      { field: 'studyCount', header: 'STUDY'  },
      { field: 'storageCount', header: 'STORAGE'  },
      { field: 'internalSize', header: 'INTERNAL SIZE'  },
      { field: 'externalSize', header: 'EXTERNAL SIZE'  },
      { field: 'totalSize', header: 'TOTAL SIZE'  },
      { field: 'aspect', header: 'ASPECT'  },
      // { field: 'size_enrich', header: 'SIZE(M^2)'  },
      // { field: 'address', header: 'ADDRESS'  },
      // { field: 'agent_code', header: 'AGENT'  },
      // { field: 'owner_code', header: 'OWNER'  },
      { field: 'price', header: 'PRICE($)'  },
      { field: 'sale_status', header: 'STATUS'  }
    ];

    
  }


  initPropertyList() {
    this.loadListDetail(this.id);
  }


  loadListDetail(id) {
    this.projectService.getProjectDetail(id).subscribe(
      (res) => {
        this.project = res;
        let filter = { propertyListId: id };
        this.enrichProjectResponse();
        this.getProperties(filter);
      });
  }

  getProperties(filter) {
    return this.propertyService.getAllProperties(filter).subscribe(
      (res) => {
        this.properties = res;
        _.each(this.properties, (property)=>{this.enrichPropertyResponse(property)});
      }
    );
  }

  goAnchor(id) {
    document.getElementById(id).scrollIntoView(true);
  }


  //https://www.cnblogs.com/zqzjs/p/5293698.html    baidu API
  // http://api.map.baidu.com/lbsapi/getpoint/index.html



  onBaiduMap(map: any) {
    let x = this.project['x'];
    let y = this.project['y'];

    //wgs84转国测局坐标
    var wgs84togcj02 = coordtransform.wgs84togcj02(x, y);
    //国测局坐标转百度经纬度坐标
    var gcj02tobd09 = coordtransform.gcj02tobd09(wgs84togcj02[0], wgs84togcj02[1]);
    console.log(gcj02tobd09);
    //baidu 121.326079,31.247389
    //google 31.2384481,121.3182744
    let point = new BMap.Point(gcj02tobd09[1], gcj02tobd09[0]);
    map.centerAndZoom(point, 15);
    var marker = new BMap.Marker(point);        // 创建标注    
    map.addOverlay(marker);                     // 将标注添加到地图中
    map.addControl(new BMap.MapTypeControl());
    // map.setCurrentCity('北京');
    map.enableScrollWheelZoom(true);
    // alert('s');

  }


  getCurrentUser() {
    this.userService.getCurrentUser().subscribe((user) => {
      this.user = user;
      console.log('current login user', this.user);
    });
  }

  //util
  enrichProjectResponse(){
    this.projectService.escapeAll(this.project, false);
  }

  enrichPropertyResponse(property){
    this.propertyService.escapeAll(property,false);
    property.size_enrich = `${property.internalSize} + ${property.externalSize} = ${property.internalSize+property.externalSize}`;
    property.totalSize = property.internalSize+property.externalSize;
  }

  getLogo(item) {
    return this.projectService.getLogo(item);
  }

  getPropertyMainImage(property) {
    return this.propertyService.getMainImageURL(property);
  }

  getMainImages(item) {
    return this.projectService.getMainImages(item);
  }

  getFullAddress(project){
    return this.projectService.getFullAddress(project);
  }

  isFeatured(){
    return this.project.featureId > 0;
  }

  back(){
    this.location.back();
  }



  navigateToPropertyDetail(property){
    this.router.navigate([`/${this.user.role}/shared/property-detail/${property.id}`],{ queryParams: { menuKey: 'house-detail', mode:'view' }});
  }

  isPropertyAvailable(property){
    return property['sale_status'] === PropertySaleStatus.FOR_SALE;
  }

  isAllowEdit(){
    return this.user.role === UserRoles.ADMIN;
  }
  onEditRow(rowData) {
    this.router.navigate([`/${this.user.role}/shared/property-detail/` + rowData.id], { queryParams: { menuKey: 'house-detail', mode: CRUD_MODE.EDIT } });
  }

  onViewRow(rowData) {
    console.log('navigate by user role', this.user);
    this.router.navigate([`/${this.user.role}/shared/property-detail/` + rowData.id], { queryParams: { menuKey: 'house-detail', mode: CRUD_MODE.VIEW } });
  }

  openLargeImage(imgSrc){
    this.previewImgSrc = imgSrc;
    this.imgPreview = true;

  }

}
